package com.dullfox.sbm.common.auth;

import com.dullfox.sbm.model.SysUser;
import com.dullfox.sbm.common.util.ConstUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Author: zengdy
 * Date: 2018/10/30
 */
@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private AuthManager authManager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        AuthIgnore annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(AuthIgnore.class);
        } else {
            return true;
        }

        //swagger-ui.html不做拦截
        if(request.getRequestURI().startsWith("/swagger") || request.getRequestURI().equals("/v2/api-docs")) {
            return true;
        }

        // 如果有@AuthIgnore注解，则不验证token
        if (annotation != null) {
            return true;
        }

        // 获取用户凭证
        String token = getToken(request);

        // token凭证为空
        if (StringUtils.isBlank(token)) {
            throw new AuthException(ConstUtil.ERROR_CODE, ConstUtil.USER_TOKEN + "不能为空");
        }

        SysUser sysUser = authManager.getUser();
        if (sysUser == null) {
            throw new AuthException(ConstUtil.ERROR_CODE_TOKEN, "该用户已过期");
        }
        authManager.refreshUser();
        return true;
    }

    public String getToken(HttpServletRequest request) {
        String token = request.getHeader(ConstUtil.USER_TOKEN);
        if (StringUtils.isBlank(token)) {
            token = request.getParameter(ConstUtil.USER_TOKEN);
        }
        return token;
    }

}
